package com.rdb.mbean;
import com.rdb.entities.*;
import com.rdb.entities.Exams;
import com.rdb.mbean.util.JsfUtil;
import com.rdb.mbean.util.PaginationHelper;
import com.rdb.sbean.ClassesFacade;
import com.rdb.sbean.ExamsFacade;
import com.rdb.sbean.MessagesFacade;
import com.rdb.sbean.StudentExamsFacade;
import com.rdb.sbean.StudentsFacade;
import com.rdb.sbean.SubjectsFacade;
import com.rdb.sbean.UsersFacade;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.DataModel;

import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import org.primefaces.event.RowEditEvent;

@ManagedBean(name = "examsController")
@SessionScoped
public class ExamsController implements Serializable {

    private Exams current;
    private DataModel items = null;
    @EJB
    private com.rdb.sbean.ExamsFacade ejbFacade;
    
    @EJB 
    private com.rdb.sbean.SubjectsFacade ejbSubjectsFacade;
    
    @EJB 
    private com.rdb.sbean.UsersFacade ejbUsersFacade;
    
    @EJB 
    private com.rdb.sbean.StudentsFacade ejbStudentsFacade;
    @EJB
    private com.rdb.sbean.StudentExamsFacade ejbStudentExamsFacade;
    
    @EJB 
    private com.rdb.sbean.ClassesFacade ejbClassesFacade;
    
    @EJB 
    private com.rdb.sbean.MessagesFacade ejbMessagesFacade;
    
    private List<Users> facList = null;
    private List<Students> listStudent;
    private Students[] listStudentSelected;
    private List<Students> listStudentCreate;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private Students studentRemove; 
    private String rollNo;
    private String studentName;
    private Courses course; 
    private Classes classe; 
    private Users searchFac;
    private Subjects searchSub;
    private Date searchFromdate;
    private Date searchTodate;
    
    
    public ExamsController() {
    }

    public Exams getSelected() {
        if (current == null) {
            current = new Exams();
            selectedItemIndex = -1;
        }
        return current;
    }

    public List<Users> getFacList() {
        return facList;
    }

    public Users getSearchFac() {
        return searchFac;
    }

    public void setSearchFac(Users searchFac) {
        this.searchFac = searchFac;
    }

    public Subjects getSearchSub() {
        return searchSub;
    }

    public void setSearchSub(Subjects searchSub) {
        this.searchSub = searchSub;
    }

    public Date getSearchFromdate() {
        return searchFromdate;
    }

    public void setSearchFromdate(Date searchFromdate) {
        this.searchFromdate = searchFromdate;
    }

    public Date getSearchTodate() {
        return searchTodate;
    }

    public void setSearchTodate(Date searchTodate) {
        this.searchTodate = searchTodate;
    }
    
    
    public List<Double> getListMark(){
        ArrayList<Double> listMrak = new ArrayList<Double>();
        for (int i = 0; i < 26; i++) {
            listMrak.add(Double.valueOf(i));
        }
        return listMrak;
    }

    public MessagesFacade getEjbMessagesFacade() {
        return ejbMessagesFacade;
    }

    public void setEjbMessagesFacade(MessagesFacade ejbMessagesFacade) {
        this.ejbMessagesFacade = ejbMessagesFacade;
    }
    
    

    public void setFacList(List<Users> facList) {
        this.facList = facList;
    }

    public List<Students> getListStudent() {
        return listStudent;
    }

    public Students getStudentRemove() {
        return studentRemove;
    }

    public void setStudentRemove(Students studentRemove) {
        this.studentRemove = studentRemove;
    }

    public void setListStudent(List<Students> listStudent) {
        this.listStudent = listStudent;
    }

    public Students[] getListStudentSelected() {
        return listStudentSelected;
    }

    public List<Students> getListStudentCreate() {
        return listStudentCreate;
    }

    public void setListStudentCreate(List<Students> listStudentCreate) {
        this.listStudentCreate = listStudentCreate;
    }

    
    public String searchExams(){
        int facId = 0;
        int subId = 0;
        if(searchFac != null){
            facId = searchFac.getUserId();
        }
        if(searchSub != null){
            subId = searchSub.getId();
        }
        
        items = new ListDataModel(ejbFacade.searchExam(facId, subId, searchFromdate, searchTodate));
        searchFac = null;
        searchSub = null;
        searchFromdate = null;
        searchTodate = null;
        return "List";
    } 
    
    public void setListStudentSelected(Students[] listStudentSelected) {
        this.listStudentSelected = listStudentSelected;
    }

    public void addStudent(){
        if(listStudentSelected !=null){
            System.out.print(listStudentSelected.length);
            for (int i = 0; i < listStudentSelected.length; i++) {
                if(listStudentCreate !=null){
                    boolean check = false;
                    for (int j = 0; j < listStudentCreate.size(); j++) {
                        if(listStudentSelected[i].getId() == listStudentCreate.get(j).getId()){
                            check = true;
                            break;
                        }
                    }
                    
                    if(!check){
                        listStudentCreate.add(listStudentSelected[i]);
                    }
                
                }else{
                    listStudentCreate = new ArrayList<Students>();
                    listStudentCreate.add(listStudentSelected[i]);
                }
            }
        }
    }
    
    public void onEdit(RowEditEvent event) {  
        StudentExams studentExams = ((StudentExams) event.getObject());
        ejbStudentExamsFacade.edit(studentExams);
        FacesMessage msg = new FacesMessage(studentExams.getStudentId().getStuName() +" change mark successful.", ((StudentExams) event.getObject()).getStudentId().getStuName() +" change mark successful"); 
        FacesContext.getCurrentInstance().addMessage(null, msg);  
    } 
    
    
    public String getRollNo() {
        return rollNo;
    }

    public void setRollNo(String rollNo) {
        this.rollNo = rollNo;
    }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public Courses getCourse() {
        return course;
    }

    public void setCourse(Courses course) {
        this.course = course;
    }

    public Classes getClasse() {
        return classe;
    }

    public void setClasse(Classes classe) {
        this.classe = classe;
    }

    
    public StudentsFacade getEjbStudentsFacade() {
        return ejbStudentsFacade;
    }

    public StudentExamsFacade getEjbStudentExamsFacade() {
        return ejbStudentExamsFacade;
    }

    public void setEjbStudentExamsFacade(StudentExamsFacade ejbStudentExamsFacade) {
        this.ejbStudentExamsFacade = ejbStudentExamsFacade;
    }

    public void setEjbStudentsFacade(StudentsFacade ejbStudentsFacade) {
        this.ejbStudentsFacade = ejbStudentsFacade;
    }

    public ClassesFacade getEjbClassesFacade() {
        return ejbClassesFacade;
    }

    public void setEjbClassesFacade(ClassesFacade ejbClassesFacade) {
        this.ejbClassesFacade = ejbClassesFacade;
    }

    public SubjectsFacade getEjbSubjectsFacade() {
        return ejbSubjectsFacade;
    }

    public void setEjbSubjectsFacade(SubjectsFacade ejbSubjectsFacade) {
        this.ejbSubjectsFacade = ejbSubjectsFacade;
    }

    public UsersFacade getEjbUsersFacade() {
        return ejbUsersFacade;
    }

    public void setEjbUsersFacade(UsersFacade ejbUsersFacade) {
        this.ejbUsersFacade = ejbUsersFacade;
    }
    
    
    public void setSelected(Exams select){
        current = select;
    }

    private ExamsFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {
                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findAll());
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }
    
    public String prepareList1() {
        recreateModel();
        return "/faces/admin/exams/List.xhtml?faces-redirect=true";
    }

    public String prepareView() {
        if(current!= null){
        return "View";
        }else{
            return prepareList();
        }
    }

    public String prepareCreate() {
        current = new Exams();
        listStudent = new ArrayList<Students>();
        listStudentSelected = null;
        listStudentCreate = new ArrayList<Students>();
        return "Create";
    }
    
    public String prepareCreate1() {
        current = new Exams();
        listStudent = new ArrayList<Students>();
        listStudentSelected = null;
        listStudentCreate = new ArrayList<Students>();
        return "/faces/admin/exams/Create.xhtml?faces-redirect=true";
    }

    public String create() {
        try {
            
            List<StudentExams> studentExamses = new ArrayList<StudentExams>();
            if(listStudentCreate != null){
            for (int i = 0; i < listStudentCreate.size(); i++) {
                StudentExams stuadd = new StudentExams();
                stuadd.setStudentId(listStudentCreate.get(i));
                stuadd.setStatus(Boolean.FALSE);
                stuadd.setMark(0.0);
                stuadd.setRemark(0.0);
                studentExamses.add(stuadd);
            }}
            
            String  newEnroll  = "Exam" + String.valueOf(1000000 + (ejbFacade.findAll().get(ejbFacade.findAll().size() - 1).getId() + 1)).substring(1);
            current.setStatus(1);
            current.setExamId(newEnroll);
            getFacade().create(current);
            
            Exams examadd = ejbFacade.getList().get(0);
            if(studentExamses != null){
                for (int i = 0; i < studentExamses.size(); i++) {
                    StudentExams exams = studentExamses.get(i);
                    exams.setExamId(examadd);
                    ejbStudentExamsFacade.create(exams);
                }
            }
            
            current.setStudentExamsList(studentExamses);
            getFacade().edit(current);
            
            Messages messages = new Messages();
            messages.setExamId(examadd);
            messages.setStatus(Boolean.FALSE);
            messages.setRegisterId(null);
            messages.setUserId(examadd.getAssignFac());
            messages.setMessages("assign teachers to grade for the " + examadd.getExamId());
            ejbMessagesFacade.create(messages);
            
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("bundle/Bundle").getString("ExamsCreated"));
            return prepareList();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("bundle/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        if(current!= null){
            int id = current.getId();
            System.out.println("id="+id);
            current = getFacade().getByID(id);
            
            if(current.getStudentExamsList() != null){
                listStudent = new ArrayList<Students>();
                rollNo = "";
                studentName = "";
                classe = null;
                listStudentSelected = null;
                listStudentCreate = new ArrayList<Students>();
                System.out.println(current.getStudentExamsList().size());
            for (int i = 0; i < current.getStudentExamsList().size(); i++) {
                listStudentCreate.add(current.getStudentExamsList().get(i).getStudentId());
            }}
            return "Edit";
        }else{
            return prepareList();
        }
        
    }

    public List<Subjects> getAllSubject(){
        return ejbSubjectsFacade.findAll();
    }
    
    public List<Classes> getAllClasses(){
        return ejbClassesFacade.findAll();
    }
    
    public List<Users> getAllUserses(){
        if(current.getSubjectId() == null){
            facList = (ejbSubjectsFacade.find(ejbSubjectsFacade.findAll().get(0).getId())).getUsersList();
        }else{
            facList = (ejbSubjectsFacade.find(current.getSubjectId().getId())).getUsersList();
        }
        return  facList;
    }
    
    public List<Users> getAllFac(){
        if(searchSub == null){
            facList = ejbUsersFacade.getfaculty();
        }else{
            facList = (ejbSubjectsFacade.find(searchSub.getId())).getUsersList();
        }
        return  facList;
    }
    
    public void changeStudentList(){
        int classId = 0;
        if(classe != null){
            classId =  classe.getId();
        }
        listStudent = ejbStudentsFacade.getStudentInExam(rollNo, studentName, classId);
    }
    
    public void removeStudent(Students stu){
        if(listStudentCreate.contains(stu)){
            listStudentCreate.remove(stu);
        }
    }
    
    public String update() {
        try {
            if(listStudentCreate != null){
            for (int i = 0; i < listStudentCreate.size(); i++) {
                boolean check = false;
                for (int j = 0; j < current.getStudentExamsList().size(); j++) {
                    if(listStudentCreate.get(i).getId() == current.getStudentExamsList().get(j).getStudentId().getId()){
                        check = true;
                        break;
                    }
                }
                if(!check){
                    StudentExams exams = new StudentExams();
                    exams.setExamId(current);
                    exams.setStudentId(listStudentCreate.get(i));
                    exams.setMark(0.0);
                    exams.setRemark(0.0);
                    exams.setStatus(Boolean.FALSE);
                    ejbStudentExamsFacade.create(exams);
                    current.getStudentExamsList().add(exams);
                }
                
               
            }
                for (int i = 0; i < current.getStudentExamsList().size(); i++) {
                    boolean check = false;
                    for (int j = 0; j < listStudentCreate.size(); j++) {
                        if(listStudentCreate.get(j).getId() == current.getStudentExamsList().get(i).getStudentId().getId()){
                            check = true;
                            break;
                        }
                    }
                    if(!check){
                        ejbStudentExamsFacade.remove(current.getStudentExamsList().get(i));
                        current.getStudentExamsList().remove(i);
                    }

                }
            
            }else{
                for (int j = 0; j < current.getStudentExamsList().size(); j++) {
                    ejbStudentExamsFacade.remove(current.getStudentExamsList().get(j));
                    current.getStudentExamsList().remove(j);
                }
            }
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("bundle/Bundle").getString("ExamsUpdated"));
            return prepareList();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("bundle/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        performDestroy();
        items = null;
        return prepareList();
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        setSelected(new Exams());
        return "List";
    }
    
    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("bundle/Bundle").getString("ExamsDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("bundle/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }
    
    @FacesConverter(forClass = Exams.class)
    public static class ExamsControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            ExamsController controller = (ExamsController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "examsController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Exams) {
                Exams o = (Exams) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Exams.class.getName());
            }
        }
    }
    
    
}
